package cn.inbot.shopadmin.module.mine.view;

import android.animation.ValueAnimator;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AlertDialog;
import androidx.core.app.ActivityOptionsCompat;
import androidx.core.widget.NestedScrollView;

import com.bumptech.glide.Glide;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.io.File;

import cn.inbot.shopadmin.R;
import cn.inbot.shopadmin.api.DemoApiFactory;
import cn.inbot.shopadmin.app.AppCacheData;
import cn.inbot.shopadmin.app.AppConfig;
import cn.inbot.shopadmin.app.AppGlobalData;
import cn.inbot.shopadmin.app.RouterUrls;
import cn.inbot.shopadmin.event.OnLoginEvent;
import cn.inbot.shopadmin.event.OnLogoutEvent;
import cn.inbot.shopadmin.util.BlurTransformation;
import cn.inbot.shopadmin.widget.SettingItemLayout;
import cn.inbot.lib.framework.EventManager;
import cn.inbot.lib.framework.annotation.InjectLayout;
import cn.inbot.lib.framework.mvvm.PBFragment;
import cn.inbot.lib.framework.router.PBRouter;
import cn.inbot.lib.framework.util.AppUtil;
import cn.inbot.lib.update.PBVersionUpdator;
import cn.inbot.lib.update.UpdateCallback;
import cn.inbot.lib.update.VersionUpdateResult;
import cn.inbot.lib.util.StringUtil;

import static cn.inbot.lib.util.ext.ToastExtKt.showToast;

/**
 * Created by shisenkun on 2021/5/10.
 */
@InjectLayout(layoutResId = R.layout.fragment_mine)
public class MineFragment extends PBFragment {

    private static final int REQUEST_CODE = 99;

    private int mLastTouchY = -1;
    private int mIvHeadPortraitBgOriginalHeight = 0;
    private ValueAnimator mRecoverIvHeadPortraitBgAnim;
    private float mScrollDamping = 0.5f;

    private SettingItemLayout srlCollect;
    private SettingItemLayout srlAbout;
    private SettingItemLayout srlAppInfo;
    private SettingItemLayout srlClearCache;
    private Button btnLogout;
    private ImageView ivHeadPortrait;
    private TextView tvUserName;
    private ImageView ivHeadPortraitBg;
    private NestedScrollView nsvRoot;

    public static MineFragment create() {
        return new MineFragment();
    }

    @Override
    public void initView(@Nullable Bundle savedInstanceState) {
        super.initView(savedInstanceState);
        EventManager.INSTANCE.register(this);
        srlCollect = getContentView().findViewById(R.id.srlCollect);
        srlAbout = getContentView().findViewById(R.id.srlAbout);
        srlAppInfo = getContentView().findViewById(R.id.srlAppInfo);
        srlClearCache = getContentView().findViewById(R.id.srlClearCache);
        btnLogout = getContentView().findViewById(R.id.btnLogout);
        ivHeadPortrait = getContentView().findViewById(R.id.ivHeadPortrait);
        tvUserName = getContentView().findViewById(R.id.tvUserName);
        ivHeadPortraitBg = getContentView().findViewById(R.id.ivHeadPortraitBg);
        nsvRoot = getContentView().findViewById(R.id.nsvRoot);
        // 为其设置点击事件
        srlCollect.setOnClickListener(v -> showToast("我的收藏"));
        srlAbout.setOnClickListener(v -> showToast("关于"));
        srlAppInfo.setOnClickListener(v -> checkUpdate());
        srlClearCache.setOnClickListener(v -> showToast("清楚缓存"));
        btnLogout.setOnClickListener(v -> {
            AppGlobalData.sLoginResult = null;
            AppCacheData.setLastLoginResultJson("");
            EventManager.INSTANCE.post(new OnLogoutEvent());
            updateAccountInfo();
        });
        ivHeadPortrait.setOnClickListener(v -> goLoginActivity());
        tvUserName.setOnClickListener(v -> goLoginActivity());

        setupHeadPortraitBgDragAnim();
        updateAccountInfo();
    }

    @Override
    public void onResume() {
        super.onResume();
        immersiveStatusBar(R.color.translucent, false);
    }

    @Override
    public void onDestroy() {
        EventManager.INSTANCE.unregister(this);
        super.onDestroy();
    }

    private void goLoginActivity() {
        PBRouter.INSTANCE.build(RouterUrls.DEMO_LOGIN)
                .withOptionsCompat(ActivityOptionsCompat.makeCustomAnimation(
                        requireActivity(), R.anim.slide_bottom_in, R.anim.slide_bottom_none))
                .navigation();
    }

    private void checkUpdate() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            //先判断是否有安装未知来源应用的权限
            boolean haveInstallPermission =
                    requireActivity().getPackageManager().canRequestPackageInstalls();
            if (!haveInstallPermission) {
                new AlertDialog.Builder(requireActivity())
                        .setTitle("消息提示")
                        .setMessage("更新应用需要打开\"应用内安装其他应用权限\",请前往设置页面打开")
                        .setCancelable(false)
                        .setPositiveButton("确定", (dialog, which)
                                        -> toInstallPermissionSettingIntent())
                        .show();
            } else {
                realCheckUpdate();
            }
        }
    }

    @SuppressLint("ClickableViewAccessibility")
    private void setupHeadPortraitBgDragAnim() {
        ivHeadPortraitBg.post(() -> mIvHeadPortraitBgOriginalHeight = ivHeadPortraitBg.getHeight());

        nsvRoot.setOnTouchListener((v, event) -> {
            switch (event.getAction()) {
                case MotionEvent.ACTION_DOWN:
                    if(mRecoverIvHeadPortraitBgAnim != null) {
                        mRecoverIvHeadPortraitBgAnim.cancel();
                    }
                    break;
                case MotionEvent.ACTION_MOVE:
                    if (mLastTouchY != -1) {
                        if (event.getY() - mLastTouchY > 5 && nsvRoot.getScrollY() == 0
                                && ivHeadPortraitBg.getHeight() <= mIvHeadPortraitBgOriginalHeight * 2
                        ) {  //向下滑动到顶了,并且背景图片高度不大于原始高度到2倍
                            ivHeadPortraitBg.getLayoutParams().height =
                                    (int) (ivHeadPortraitBg.getHeight() + (event.getY() - mLastTouchY) * mScrollDamping);
                            ivHeadPortraitBg.requestLayout();
                        } else if (event.getY() - mLastTouchY < -5
                                && ivHeadPortraitBg.getHeight() - mIvHeadPortraitBgOriginalHeight > 0
                        ) {  //向上滑动，并且头像背景大于原始高度
                            ivHeadPortraitBg.getLayoutParams().height =
                                    (int) (ivHeadPortraitBg.getHeight() + (event.getY() - mLastTouchY) * mScrollDamping);
                            ivHeadPortraitBg.requestLayout();
                        }
                    }
                    break;
                case MotionEvent.ACTION_UP:
                    if (ivHeadPortraitBg.getHeight() - mIvHeadPortraitBgOriginalHeight > 0) {  //松手后，并且头像背景大于原始高度
                        doRecoverIvHeadPortraitBgAnim();
                    }
                    break;
            }
            mLastTouchY = (int) event.getY();
            return false;
        });
    }

    private void doRecoverIvHeadPortraitBgAnim() {
        if(mRecoverIvHeadPortraitBgAnim != null) {
            mRecoverIvHeadPortraitBgAnim.cancel();
        }
        mRecoverIvHeadPortraitBgAnim =
                ValueAnimator.ofInt(ivHeadPortraitBg.getHeight(), mIvHeadPortraitBgOriginalHeight);
        mRecoverIvHeadPortraitBgAnim.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                ivHeadPortraitBg.getLayoutParams().height = (int) animation.getAnimatedValue();
                ivHeadPortraitBg.requestLayout();
            }
        });
        mRecoverIvHeadPortraitBgAnim.start();
    }

    /**
     * 开启安装未知来源权限
     */
    @RequiresApi(api = Build.VERSION_CODES.O)
    private void toInstallPermissionSettingIntent() {
        Uri packageURI = Uri.parse("package:" + AppUtil.getPackageName(requireActivity()));
        Intent intent = new Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES, packageURI);
        startActivityForResult(intent, REQUEST_CODE);
    }

    private void realCheckUpdate() {
        //还需要在manifext.xml配置file provider
        PBVersionUpdator.INSTANCE.appType(AppConfig.APP_TYPE)
                .appVersion(AppConfig.APP_VERSION)
                .serverIp(AppConfig.PADBOT_SERVER_URL)
                .okHttpClientBuilder(DemoApiFactory.getInstance().demoOkHttpClientBuilder)
                .retrofitBuilder(DemoApiFactory.getInstance().demoRetrofitBuilder)
                .commissionUpdateUi(requireActivity(), 0.7f, R.mipmap.ic_update_top)
                .checkUpdate(new UpdateCallback() {
                    @Override
                    public void onStartCheckUpdate() {

                    }

                    @Override
                    public void onNeedUpdate(@NotNull VersionUpdateResult response) {

                    }

                    @Override
                    public void onNotNeedUpdate() {
                        showToast("当前已经是最新版本");
                    }

                    @Override
                    public void onStartDownload() {

                    }

                    @Override
                    public void onDownloadProgress(long downloadedLength, long totalLength, int progress) {

                    }

                    @Override
                    public void onDownloadCompleted(@NotNull File file) {

                    }

                    @Override
                    public void onError(@NotNull String errorMessage) {
                        showToast("检查更新出错,请重试");
                    }
                });
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(OnLoginEvent event) {
        updateAccountInfo();
    }

    private void updateAccountInfo() {
        if (AppGlobalData.sLoginResult != null) {
            if (StringUtil.isNotEmpty(AppGlobalData.sLoginResult.getMiddleLogoId())) {
                Glide.with(requireActivity())
                        .load(AppConfig.HEADPORTRAIT_URL_PREFIX + AppGlobalData.sLoginResult.getMiddleLogoId())
                    .into(ivHeadPortrait);
            }
            if (StringUtil.isNotEmpty(AppGlobalData.sLoginResult.getLargeLogoId())) {
                Glide.with(requireActivity())
                        .load(AppConfig.HEADPORTRAIT_URL_PREFIX + AppGlobalData.sLoginResult.getLargeLogoId())
                    .bitmapTransform(new BlurTransformation(requireActivity()))
                        .into(ivHeadPortraitBg);
            }
            tvUserName.setText(AppGlobalData.sLoginResult.getNickname());
            btnLogout.setVisibility(View.VISIBLE);
            ivHeadPortrait.setClickable(false);
            tvUserName.setClickable(false);
        } else {
            ivHeadPortrait.setImageResource(R.mipmap.ic_head_portrait_default);
            ivHeadPortraitBg.setImageResource(R.mipmap.ic_head_portrait_bg);
            ivHeadPortrait.setClickable(true);
            tvUserName.setClickable(true);
            tvUserName.setText("点击登陆");
            btnLogout.setVisibility(View.GONE);
        }
    }

}
